package com.guli.gulimall.gulimallware.service.impl;

import com.guli.common.utils.*;
import com.guli.gulimall.gulimallware.entity.PurchaseDetailEntity;
import com.guli.gulimall.gulimallware.service.PurchaseDetailService;
import com.guli.gulimall.gulimallware.service.WareSkuService;
import com.guli.gulimall.gulimallware.vo.MergeVo;
import com.guli.gulimall.gulimallware.vo.PurchaseDoneVo;
import com.guli.gulimall.gulimallware.vo.PurchaseItemDoneVo;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.gulimall.gulimallware.dao.PurchaseDao;
import com.guli.gulimall.gulimallware.entity.PurchaseEntity;
import com.guli.gulimall.gulimallware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private  WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceived(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> purchaseEntityQueryWrapper = new QueryWrapper<PurchaseEntity>();
        purchaseEntityQueryWrapper.eq("status", WareConstant.PurchaseSeStatus.Created.getCode()).or().eq("status", WareConstant.PurchaseSeStatus.ASSIGNED.getCode());
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                purchaseEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public R mergePurchase(MergeVo vo) {
        Long purchaseId = vo.getPurchaseId();
        if (null == purchaseId) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseSeStatus.Created.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //todo 确认采购单状态是0，1才可以合并

        List<Long> items = vo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntityList = items.stream().map(i -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(PurchaseDetailsStatusEnum.PurchaseSeStatus.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).filter(it->{
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>().eq("id", it.getId()));
            return purchaseDetailEntities.get(0).getStatus()== PurchaseDetailsStatusEnum.PurchaseSeStatus.Created.getCode()||
                    purchaseDetailEntities.get(0).getStatus()== PurchaseDetailsStatusEnum.PurchaseSeStatus.ASSIGNED.getCode();
        }).collect(Collectors.toList());

        if(purchaseDetailEntityList.size() > 0){
            purchaseDetailService.updateBatchById(purchaseDetailEntityList);
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setId(purchaseId);
            boolean t = this.updateById(purchaseEntity);
            if(t){
                return R.ok().put("data","合并成功");
            }

        }
        return R.error().put("data","错误信息");
    }

    @Transactional
    @Override
    public R receivelist(List<Long> ids) {

        /**
         * 1.确认当前采购单是新建或者已分配状态
         * 2 改变采购单的状态
         * 3 改变采购项的状态
         */
        //1.确认当前采购单是新建或者已分配状态
        //2 改变采购单的状态
        List<PurchaseEntity> purchaseEntityStream = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item -> item.getStatus() == WareConstant.PurchaseSeStatus.Created.getCode() ||
                item.getStatus() == WareConstant.PurchaseSeStatus.ASSIGNED.getCode()).map(item->{
                    item.setStatus(WareConstant.PurchaseSeStatus.REICIEVED.getCode());
                    item.setUpdateTime(new Date());
                    return item;
        }).collect(Collectors.toList());
         AtomicInteger count = new AtomicInteger();
        if(purchaseEntityStream.size()>0){

            // 3 改变采购项的状态
            purchaseEntityStream.forEach(item->{
                List<PurchaseDetailEntity> entities = this.purchaseDetailService.listDetailPurchaseId(item.getId());
                List<PurchaseDetailEntity> collect = entities.stream().map(entity -> {
                    PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                    purchaseDetailEntity.setId(entity.getId());
                    purchaseDetailEntity.setStatus(PurchaseDetailsStatusEnum.PurchaseSeStatus.BUYING.getCode());
                    return purchaseDetailEntity;
                }).collect(Collectors.toList());
                if(collect.size()>0){
                    this.purchaseDetailService.updateBatchById(collect);
                    count.addAndGet(collect.size());
                }
            });
            if(count.get()>0){
                this.updateBatchById(purchaseEntityStream);
            }
            return  count.get()>0?R.ok().put("data","接单成功:"+count): R.error().put("data","接单失败");
        }else{
            log.debug("订单为空");
            return  R.error().put("data","接单失败");
        }
    }

    @Override
    @Transactional
    public R done(PurchaseDoneVo purchaseDoneVo) {

        //2 改变采购项的状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> purchaseDoneVoItems = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for(PurchaseItemDoneVo item : purchaseDoneVoItems){
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseSeStatus.REICIEVED.getCode()){
                flag =false;
                purchaseDetailEntity.setStatus(item.getStatus());
            }else{
                purchaseDetailEntity.setStatus(PurchaseDetailsStatusEnum.PurchaseSeStatus.FINISED.getCode());
                //3 将成功采购的进行入库
                PurchaseDetailEntity purchaseDetailServiceById = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(purchaseDetailServiceById.getSkuId(),purchaseDetailServiceById.getWareId(),purchaseDetailServiceById.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            updates.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(updates);

        //1 改变采购单状态
        Long id = purchaseDoneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseSeStatus.FINISED.getCode():WareConstant.PurchaseSeStatus.HASEERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
        return R.ok();
    }

}